import { defineStore } from "pinia";
import { deepClone } from '@/utils/index'
import {tabMap} from '@/data/router.js'
// tab最多个数
const pageTabMax = 15;

const useTagsViewStore = defineStore(
  'tags-view',
  {
    state: () => ({
      visitedViews: [],
      cachedViews: [],
      iframeViews: [],
      installAppMap: [],  //已加载的微应用
      activeTab: {}, //当前活跃tab索引
      fromView: null, // 记录上一个路由
    }),
    actions: {
      // 添加缓存 tab
      async addView(view, currentRoute) {
        // 跳转外部链接
        if (view?.path == "/publish/ebay/index"){
          view.name = 'publishEbay'
          setTimeout(() => {
            this.delView(view)
          }, 1000);
        }
        await this.addVisitedView(view, currentRoute)
        await this.addCachedView(view)
      },
      addIframeView(view) {
        if (this.iframeViews.some(v => v.path === view.path)) return
        if (!view.meta.title) return
        this.iframeViews.push(
          Object.assign({}, view, {
            title: view.meta?.title || 'no-name'
          })
        )
      },
      // 添加缓存 tab
      async addVisitedView(view, currentRoute) {
        // 操作当前激活菜单
        if (this.visitedViews.some(v => v.path === view.path)) return
        if (!view.meta.title) return
        // 添加tab
        this.visitedViews.push(Object.assign({}, view, { title: view.meta?.title || 'no-name' }))

        if (!currentRoute) {
          this.activeTab = view
        }
        // 保持主应用 home 在第一位
        const indexObjectIndex = this.visitedViews.findIndex(item => item.name === "Index");
        if (indexObjectIndex !== -1) {
          const indexObject = this.visitedViews.splice(indexObjectIndex, 1)[0];
          this.visitedViews.unshift(indexObject);
        }

        function uniqueArray(arr) {
          let obj = {}
          arr = arr.reduce(function (a, b) {
            obj[b.path] ? '' : obj[b.path] = true && a.push(b);
            return a;
          }, [])
          return arr;
        }
        // 缓存tab数量超过 tab最多个数
        if (this.visitedViews.length > pageTabMax){
          let tabList = this.visitedViews
          let removeItem = tabList[0]
          if (removeItem.meta?.affix) {
            removeItem = tabList[1]
          }
          await this.delView(removeItem)
        }
        
        this.visitedViews = uniqueArray(this.visitedViews)
        // if (this.visitedViews.length < pageTabMax) {
        //   this.visitedViews.push(
        //     Object.assign({}, view, {
        //       title: view.meta?.title || 'no-name'
        //     })
        //   )
        //   this.visitedViews = uniqueArray(this.visitedViews)
        // } else {
        //   let tabList = this.visitedViews
        //   let removeItem = tabList[0]
        //   if (removeItem.meta?.affix) {
        //     removeItem = tabList[1]
        //   }

        //   // const appName = removeItem.appName

        //   // if (appName === 'main') {
        //   //   // getters.keepAliveList['iframe'] = getters.keepAliveList['iframe'].filter((item) => item !== removeItem.name)
        //   // } else {
        //   //   // 否则是微应用
        //   //   let installApp = {
        //   //     ...this.installAppMap
        //   //   }
        //   //   // 如果微应用没有活跃的tab了就销毁 并且 跳转的不是当前微应用的页面
        //   //   const hasChildApp = tabList.slice(tabList.length - pageTabMax + 2, tabList.length).some((item) => item.appName === appName) && appName !== view.appName
        //   //   if (!hasChildApp && appName !== view.appName) {
        //   //     console.error('🚀🚀🚀微页面[' + appName + ']已经销毁了!!!')
        //   //     installApp[appName].unmount()
        //   //     delete installApp[appName]
        //   //     this.pushInstallAppMap(installApp)
        //   //     this.clearMoudleQiankunAppLifeCycles(appName)
        //   //   } else {

        //   //     // installApp[appName] && installApp[appName].update({
        //   //     //   routerEvent: {
        //   //     //     path: removeItem.path,
        //   //     //     type: 'close'
        //   //     //   }
        //   //     // })

        //   //     installApp[appName].mountPromise.then(()=>{
        //   //       installApp[appName].update({
        //   //         routerEvent: {
        //   //           path: removeItem.path,
        //   //           type: 'close'
        //   //         }
        //   //       })
        //   //     })

        //   //   }
        //   // }
        //   this.delView(removeItem)
        //   this.visitedViews.push(
        //     Object.assign({}, view, {
        //       title: view.meta?.title || 'no-name'
        //     })
        //   )
        //   this.visitedViews = uniqueArray(this.visitedViews)
        // }
      },
      // 添加缓存 tab
      addCachedView(view) {
        if (this.cachedViews.includes(view.name)) return
        // 临时方案  主页 no-name 问题
        if (tabMap[view.path]) return
        this.cachedViews.push(
          Object.assign({}, view, {
            title: view.meta?.title || 'no-name'
          })
        )
      },
      // 删除单个tab缓存
      delView(view) {
        return new Promise(resolve => {
          setTimeout(async() => {
           await this.delVisitedView(view)
           await this.delCachedView(view)
            resolve({
              visitedViews: [...this.visitedViews],
              cachedViews: [...this.cachedViews]
            })
          }, 0);
        })
      },
      // 删除单个tab缓存
      delVisitedView(view) {
        return new Promise(resolve => {
          console.log('delVisitedView');
          console.log(this.visitedViews);
          // -------------------- 不会进入  visitedViews数量 在后续代码删除 --------------------
          // if (this.visitedViews.length === 1) {
          //   console.log(100867);
          //   this.visitedViews = []
          //   try {
          //     // 销毁所有微应用
          //     for (let name in this.installAppMap) {
          //       let app = this.installAppMap[name]
          //       console.warn('🚀🚀🚀微页面[' + name + ']已经销毁了!!!  1 !!!')
          //       if (app && app.getStatus() === 'MOUNTED') {
          //         app.unmount()
          //         this.clearMoudleQiankunAppLifeCycles(name)
          //       }
          //     }
          //   } catch (error) {
          //     console.error('delVisitedView error ------>>>>', error)
          //   }
          //   this.pushInstallAppMap({})
          //   resolve([...this.visitedViews])
          //   //跳转首页
          //   return
          // }

          let nowActiveTab = this.activeTab
          let tabList = this.visitedViews
          let frist = tabList[0]
          let last = tabList[tabList.length - 1]

          // 无用代码 注释
          // let activeTab = null;
          if (nowActiveTab.path === view.path) {
            // 如果删除的是当前活跃的tab
            tabList = tabList.filter((item) => {
              if (nowActiveTab.path !== item.path) {
                return item
              }
            })
            // 无用代码 注释
            // activeTab = tabList[tabList.length - 1]
          } else if (view.path === last['path']) {
            // 先对比尾部
            tabList.pop()
            // 无用代码 注释
            // activeTab = tabList[tabList.length - 1]
          } else if (view.path === frist['path']) {
            // 再对比头部
            tabList.shift()
            // 无用代码 注释
            // activeTab = nowActiveTab
          } else {
            // 都匹配不上就对比中间
            let findIndex = -1
            tabList = tabList.filter((item, index) => {
              if (item.path !== view.path) {
                return item
              } else {
                findIndex = index > 1 ? index : 1
              }
            })
            // 无用代码 注释
            // activeTab = nowActiveTab
          }

          const appName = view.appName
          // 如果是主应用
          if (appName === 'main') {
            // getters.keepAliveList['main'] = getters.keepAliveList['main'].filter((item) => item !== data.name)
          } else {
            // 否则是微应用
            let installApp = this.installAppMap
            
            // 如果微应用没有活跃的tab了就销毁
            if (!tabList.some((item) => item.appName === appName)) {
              try {
                console.warn('🚀🚀🚀微页面[' + appName + ']已经销毁了!!!')
                if (installApp[appName].getStatus() === 'MOUNTED') {
                  installApp[appName].unmount()
                }
                delete installApp[appName]
                this.clearMoudleQiankunAppLifeCycles(appName)
                this.pushInstallAppMap(installApp)
              } catch (error) {
                console.log(error)
              }
            } else {
                // installApp[appName].mountPromise.then(()=>{
                //   if (installApp[appName].getStatus() === 'MOUNTED') {
                //     installApp[appName].update({
                //       routerEvent: {
                //         path: view.path,
                //         type: 'close'
                //       }
                //     })
                //   }
                // })
              installApp[appName].update({
                routerEvent: {
                  path: view.path,
                  type: 'close'
                }
              })
            }
          }

          this.cachedViews = tabList
          this.visitedViews = tabList
          // 无用代码 注释
          // if (activeTab.path !== nowActiveTab.path) {
            // this.router.replace(activeTab.path)
            // this.activeTab = activeTab
          // }

          this.iframeViews = this.iframeViews.filter(item => item.path !== view.path)
          resolve([...this.visitedViews])
        })
      },
      delIframeView(view) {
        return new Promise(resolve => {
          this.iframeViews = this.iframeViews.filter(item => item.path !== view.path)
          resolve([...this.iframeViews])
        })
      },
      // 删除单个tab缓存
      async delCachedView(view) {
        return new Promise(resolve => {
          const index = this.cachedViews.indexOf(view.name)
          index > -1 && this.cachedViews.splice(index, 1)

          resolve([...this.cachedViews])
        })
      },
      // 关闭其他tab页签
      delOthersViews(view) {
        return new Promise(resolve => {
          this.delOthersVisitedViews(view)
          this.delOthersCachedViews(view)
          resolve({
            visitedViews: [...this.visitedViews],
            cachedViews: [...this.cachedViews]
          })
        })
      },
      // 关闭其他tab页签
      delOthersVisitedViews(view) {
        return new Promise(async resolve => {
          const affectedTabs = this.visitedViews.filter(v => !v.meta.affix && v.path != view.path);
          this.visitedViews = this.visitedViews.filter(v => {
            return v.meta.affix || v.path === view.path
          })

          for (let name in this.installAppMap) {
            let app = this.installAppMap[name]
            const index = this.visitedViews.findIndex(v => v.appName == name)
            if (index == -1) {
              console.warn('销毁子应用' + name)
              app.unmount()
              delete this.installAppMap[name]
            } else {
              await this.closeAffectedTabs(affectedTabs)
            }
          }
          this.activeTab = view

          this.iframeViews = this.iframeViews.filter(item => item.path === view.path)
          resolve([...this.visitedViews])
        })
      },
      // 关闭其他tab页签
      delOthersCachedViews(view) {
        return new Promise(resolve => {
          const index = this.cachedViews.indexOf(view.name)
          if (index > -1) {
            this.cachedViews = this.cachedViews.slice(index, index + 1)
          } else {
            this.cachedViews = []
          }
          resolve([...this.cachedViews])
        })
      },
      // 关闭所有tab页签
      delAllViews() {
        return new Promise(resolve => {
          this.delAllCachedViews()
          this.delAllVisitedViews()
          resolve({
            visitedViews: [...this.visitedViews],
            cachedViews: [...this.cachedViews]
          })
        })
      },
      // 关闭所有tab页签
      delAllVisitedViews() {
        return new Promise(resolve => {
          this.visitedViews = this.visitedViews.filter(tag => tag.meta.affix)

            try {
              // 销毁所有微应用
              for (let name in this.installAppMap) {
                console.error('🚀🚀🚀微页面[' + name + ']已经销毁了!!!  1 !!!')
                this.installAppMap[name].unmount()
                this.clearMoudleQiankunAppLifeCycles(name)
              }
            } catch (error) {
              console.error('delAllVisitedViews', error)
            }
            // this.installAppMap.head_procedure.unmountPromise()
            this.iframeViews = []
            this.pushInstallAppMap({})
            resolve([])
            //跳转首页
          // this.iframeViews = []
          // resolve([...this.visitedViews])
        })
      },
      // 关闭所有tab页签
      delAllCachedViews(view) {
        return new Promise(resolve => {
          this.cachedViews = []
          resolve([...this.cachedViews])
        })
      },
      // 修改tab页签
      updateVisitedView(view) {
        for (let v of this.visitedViews) {
          if (v.path === view.path) {
            v = Object.assign(v, view)
            break
          }
        }
      },
      // 关闭右侧tab页签
      delRightTags(view) {
        return new Promise(async resolve => {
          const index = this.visitedViews.findIndex(v => v.path === view.path)
          if (index === -1) {
            return
          }
          const affectedTabs = this.visitedViews.filter((item, idx) => {
            return idx > index
          })
          this.visitedViews = this.visitedViews.filter((item, idx) => {
            if (idx <= index || (item.meta && item.meta.affix)) {
              return true
            }
            const i = this.cachedViews.indexOf(item.name)
            if (i > -1) {
              this.cachedViews.splice(i, 1)
            }
            if (item.meta.link) {
              const fi = this.iframeViews.findIndex(v => v.path === item.path)
              this.iframeViews.splice(fi, 1)
            }
            return false
          })

          for (let name in this.installAppMap) {
            let app = this.installAppMap[name]
            const index = this.visitedViews.findIndex(v => v.appName == name)
            if (index == -1) {
              console.warn('销毁子应用' + name)
              app.unmount()
              delete this.installAppMap[name]
            } else {
              await this.closeAffectedTabs(affectedTabs)
            }
          }
          resolve([...this.visitedViews])
        })
      },
      // 关闭左侧tab页签
      delLeftTags(view) {
        return new Promise(async resolve => {
          const index = this.visitedViews.findIndex(v => v.path === view.path)
          if (index === -1) {
            return
          }
          const affectedTabs = this.visitedViews.filter((item, idx) => {
            return idx < index
          })

          this.visitedViews = this.visitedViews.filter((item, idx) => {
            if (idx >= index || (item.meta && item.meta.affix)) {
              return true
            }
            const i = this.cachedViews.indexOf(item.name)
            if (i > -1) {
              this.cachedViews.splice(i, 1)
            }
            if (item.meta.link) {
              const fi = this.iframeViews.findIndex(v => v.path === item.path)
              this.iframeViews.splice(fi, 1)
            }
            return false
          })

          for (let name in this.installAppMap) {
            let app = this.installAppMap[name]
            const index = this.visitedViews.findIndex(v => v.appName == name)
            if (index == -1) {
              console.warn('销毁子应用' + name)
              app.unmount()
              delete this.installAppMap[name]
            } else {
              await this.closeAffectedTabs(affectedTabs)
            }
          }
          resolve([...this.visitedViews])
        })
      },

      pushInstallAppMap(view) {
        this.installAppMap = view
      },
      addFromView(view) {
        this.fromView = Object.assign({}, view)
      },
      async closeAffectedTabs(affectedTabs) {
        return new Promise(async resolve => {
          for (let v of affectedTabs) {
            if (this.installAppMap[v.appName]) {
              await this.awaitFn()
              await this.installAppMap[v.appName].mountPromise.then(()=> {
                if (this.installAppMap[v.appName].getStatus() === 'MOUNTED') {
                  console.warn('MOUNTED 正常销毁！')
                  this.installAppMap[v.appName].update({
                    routerEvent: {
                      path: v.path,
                      type: 'close'
                    }
                  })
                }
              })
            }
          }
          resolve()
        })
      },
      async awaitFn(affectedTabs) {
        return new Promise(async resolve => {
          setTimeout(() => {
            resolve()
          }, 100);
        })
      },
      clearMoudleQiankunAppLifeCycles(name) {
        if (window.moudleQiankunAppLifeCycles) delete window.moudleQiankunAppLifeCycles[name]
      }
    }
  })

export default useTagsViewStore
